package com.promis.widget.MyPopupWindow;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.promis.util.CollectionUtils;
import com.promis.util.ColorUtils;
import com.promis.widget.R;

import java.util.List;

/**
 * Created by jidanbo on 2018/3/12.
 */

public class PopupWindowAdapter extends RecyclerView.Adapter<PopupWindowAdapter.ViewHolder> {

    private Context context;
    private List<String> stringList;
    private PopupWindowAdapter.OnItemClickListener listener;

    private int flag = -1;

    public PopupWindowAdapter(Context context) {
        this.context = context;
    }

    @Override
    public PopupWindowAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.adapter_popupwindow, parent, false);
        return new PopupWindowAdapter.ViewHolder(context, view, listener);
    }

    @Override
    public void onBindViewHolder(PopupWindowAdapter.ViewHolder holder, int position) {
        if (CollectionUtils.isNullOrEmpty(stringList)) return;

        if(flag >= 0){
            if((position == flag)){
                holder.txtvTime.setTextColor(ColorUtils.getColor(context, R.color.popupwindow_selected));
            }else{
                holder.txtvTime.setTextColor(ColorUtils.getColor(context, R.color.text_black));
            }
        }
        holder.txtvTime.setText(stringList.get(position));
    }

    @Override
    public int getItemCount() {
        if (CollectionUtils.isNullOrEmpty(stringList)) return 0;
        else return stringList.size();
    }

    public void notifyDataSetChanged(List<String> stringList) {
        this.stringList = stringList;
        notifyDataSetChanged();
    }

    public void notifyDataSetChanged(List<String> stringList, int flag) {
        this.stringList = stringList;
        this.flag = flag;
        notifyDataSetChanged();
    }

    public void setOnItemClickListener(PopupWindowAdapter.OnItemClickListener listener) {
        this.listener = listener;
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        private TextView txtvTime;

        public ViewHolder(Context context, View view, final PopupWindowAdapter.OnItemClickListener listener) {
            super(view);
            txtvTime = view.findViewById(R.id.adapter_popupwindow_txtv_time);

            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(listener != null) listener.onClick(v, getLayoutPosition());
                }
            });
        }
    }

    public static interface OnItemClickListener {
        void onClick(View view, int position);
    }
}
